const AppError = require('../utils/appError');
const handleJWTExpiredError = ()=>new AppError('the token has expired,Please log in again',401)
const handleJWTError = () => new AppError('Invalid token,Please log in', 401);
const handleDuplicateFieldsDB = (err) => {
  // let value = err.errmsg.match(/(["'])(\\?.)*?\1)/)[0];
  const value = `{%temp%}`;
  const message = `Duplicate field value:${value},Please use another value`;
  return new AppError(message, 400);
};
const handleCastErrorBD = (err) => {
  const message = `Invalid ${err.path} :${err.value}`;
  return new AppError(message, 400);
};
const sendErrorDev = (err, res) => {
  res.status(err.statusCode).json({
    status: err.status,
    message: err.message,
    error: err,
    stack: err.stack,
  });
};
const sendErrorPro = (err, res) => {
  if (err.isOperational) {
    res.status(err.statusCode).json({
      status: err.status,
      message: err.message,
    });
  } else {
    console.log('ERROR', err);
    res.status(500).json({
      status: 'error',
      message: 'Something went very wrong',
    });
  }
};

module.exports = (err, req, res, next) => {
  // console.log(err.stack)
  err.statusCode = err.statusCode || 500;
  err.status = err.status || 'error';
  if (process.env.NODE_ENV === 'development') {
    sendErrorDev(err, res);
  } else if (process.env.NODE_ENV === 'production') {
    let error = { ...err };
    if (error.name === 'CastError') error = handleCastErrorBD(error);
    if (error.code === 11000) error = handleDuplicateFieldsDB(error);
    //TODO:3

    if (error.name === 'JsonWebTokenError') error = handleJWTError(error);
    if (error.name === 'TokenExpiredError')
      error = handleJWTExpiredError(error);
    sendErrorPro(error, res);
  }
};
